<template>
  <div :class="{ hasTagsView: needTagsView }" class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单ID" prop="ordersId">
              <el-input v-model="queryParams.ordersId" placeholder="请输入订单ID" clearable @keyup.enter="handleQuery" @blur="handleQuery"/>
            </el-form-item>
            <el-form-item label="商品id/套餐id" prop="goodsId">
              <el-input v-model="queryParams.goodsId" placeholder="请输入商品id/套餐id" clearable @keyup.enter="handleQuery" @blur="handleQuery"/>
            </el-form-item>
            <el-form-item label="商品名称/套餐名称" prop="goodsName">
              <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称/套餐名称" clearable @keyup.enter="handleQuery" @blur="handleQuery"/>
            </el-form-item>
            <el-form-item label="已选列表" prop="selected">
              <el-input v-model="queryParams.selected" placeholder="请输入已选列表" clearable @keyup.enter="handleQuery" @blur="handleQuery"/>
            </el-form-item>
            <el-form-item label="数量" prop="number">
              <el-input v-model="queryParams.number" placeholder="请输入数量" clearable @keyup.enter="handleQuery" @blur="handleQuery"/>
            </el-form-item>
            <el-form-item label="金额" prop="amount">
              <el-input v-model="queryParams.amount" placeholder="请输入金额" clearable @keyup.enter="handleQuery" @blur="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="card-content" ref="cardRef">
      <template #header>
        <el-row :gutter="10" class="mb8" ref="headerRef">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['customer:orderDetail:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['customer:orderDetail:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['customer:orderDetail:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['customer:orderDetail:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="orderDetailList" :height="tableHeight" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" width="50" type="index" align="center">
              <template #default="scope">
                  <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
              </template>
          </el-table-column>
        <el-table-column label="主键" align="center" prop="orderDetailId" v-if="true" />
        <el-table-column label="订单ID" align="center" prop="ordersId" />
        <el-table-column label="图片" align="center" prop="image" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.image" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="商品id/套餐id" align="center" prop="goodsId" />
        <el-table-column label="商品名称/套餐名称" align="center" prop="goodsName" />
        <el-table-column label="已选列表" align="center" prop="selected" />
        <el-table-column label="数量" align="center" prop="number" />
        <el-table-column label="金额" align="center" prop="amount" />
        <el-table-column label="操作" fixed="right" align="center" min-width="130" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button plain circle type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['customer:orderDetail:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button plain circle type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['customer:orderDetail:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
      <div class="page-content">
          <pagination
              v-show="total>0"
              v-model:limit="queryParams.pageSize"
              v-model:page="queryParams.pageNum"
              :total="total"
              @pagination="getList"
          />
      </div>
    <!-- 添加或修改订单明细对话框 -->
    <el-drawer :title="drawer.title" v-model="drawer.visible" append-to-body close-on-click-modal>
      <el-form ref="orderDetailFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单ID" prop="ordersId">
          <el-input v-model="form.ordersId" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="商品id/套餐id" prop="goodsId">
          <el-input v-model="form.goodsId" placeholder="请输入商品id/套餐id" />
        </el-form-item>
        <el-form-item label="商品名称/套餐名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称/套餐名称" />
        </el-form-item>
        <el-form-item label="已选列表" prop="selected">
            <el-input v-model="form.selected" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="OrderDetail" lang="ts">
import { listOrderDetail, getOrderDetail, delOrderDetail, addOrderDetail, updateOrderDetail } from '@/api/customer/orderDetail';
import { OrderDetailVO, OrderDetailQuery, OrderDetailForm } from '@/api/customer/orderDetail/types';
import useSettingsStore from "@/store/modules/settings";
import {useTableHeight} from "@/utils/useTableHeight";

/*计算表格高度*/
const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(null);
const { tableHeight } = useTableHeight(cardRef, [headerRef]);
const settingsStore = useSettingsStore()
const needTagsView = computed(() => settingsStore.tagsView);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const orderDetailList = ref<OrderDetailVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const orderDetailFormRef = ref<ElFormInstance>();

const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});

const initFormData: OrderDetailForm = {
  orderDetailId: undefined,
  ordersId: undefined,
  image: undefined,
  goodsId: undefined,
  goodsName: undefined,
  selected: undefined,
  number: undefined,
  amount: undefined
}
const data = reactive<PageData<OrderDetailForm, OrderDetailQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    ordersId: undefined,
    image: undefined,
    goodsId: undefined,
    goodsName: undefined,
    selected: undefined,
    number: undefined,
    amount: undefined,
    params: {
    }
  },
  rules: {
    orderDetailId: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    ordersId: [
      { required: true, message: "订单ID不能为空", trigger: "blur" }
    ],
    image: [
      { required: true, message: "图片不能为空", trigger: "blur" }
    ],
    goodsId: [
      { required: true, message: "商品id/套餐id不能为空", trigger: "blur" }
    ],
    goodsName: [
      { required: true, message: "商品名称/套餐名称不能为空", trigger: "blur" }
    ],
    selected: [
      { required: true, message: "已选列表不能为空", trigger: "blur" }
    ],
    number: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单明细列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrderDetail(queryParams.value);
  orderDetailList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
    drawer.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  orderDetailFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderDetailVO[]) => {
  ids.value = selection.map(item => item.orderDetailId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
    drawer.visible = true;
    drawer.title = "添加订单明细";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderDetailVO) => {
  reset();
  const _orderDetailId = row?.orderDetailId || ids.value[0]
  const res = await getOrderDetail(_orderDetailId);
  Object.assign(form.value, res.data);
    drawer.visible = true;
    drawer.title = "修改订单明细";
}

/** 提交按钮 */
const submitForm = () => {
  orderDetailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.orderDetailId) {
        await updateOrderDetail(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addOrderDetail(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
        drawer.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: OrderDetailVO) => {
  const _orderDetailIds = row?.orderDetailId || ids.value;
  await proxy?.$modal.confirm('是否确认删除订单明细编号为"' + _orderDetailIds + '"的数据项？').finally(() => loading.value = false);
  await delOrderDetail(_orderDetailIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('customer/orderDetail/export', {
    ...queryParams.value
  }, `orderDetail_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
